<?php
/**
 * Created by PhpStorm.
 * User: fang_
 * Date: 2016/9/30
 * Time: 11:14
 */
require 'vendor/autoload.php';
use Sunra\PhpSimple\HtmlDomParser;
$client = new GuzzleHttp\Client();

// 进入单个学生的批阅页面
if (!empty($_GET['hwaid']) && !empty($_COOKIE['session_id'] )) {
    $res = $client->request('POST',
        'http://e-learning.hznu.edu.cn/eol/common/hw/hwanswer.comment.jsp?hwaid='.$_GET['hwaid'],
        [
            'headers' => ['Cookie' => $_COOKIE['session_id']]
        ]
    );

    $html = HtmlDomParser::str_get_html(iconv('GBK', 'UTF-8', $res->getBody()));
    if ($_GET['_r'] == 0)
    {
        //echo $html;
        // input 中的链接地址
        $files = $html->find('table#table2 tbody td.text input', 0)->value;
        // 寻找id
        $files = explode('id=',$files);
        array_shift($files);
        
        if (count($files) > 1)
        {
            $i = 0;
            foreach ($files as $file)
            {
                $files_id =  strstr($file, '&quot', true);

                echo '<p><a href="'.'http://e-learning.hznu.edu.cn/eol/common/ckeditor/openfile.jsp?id='.
                    $files_id.'" target="_blank">'.'下载文件'.$i.'</a></p>';
                $i++;
            }
        }
        else
        {
            $files_id = strstr($files[0], '&quot', true);
            $res = $client->request('GET',
                'http://e-learning.hznu.edu.cn/eol/common/ckeditor/openfile.jsp?id='.$files_id
            );


            // 重写header
            $filename = strstr(iconv('GBK', 'UTF-8',($res->getHeader('Content-Disposition'))[0]),'"');
            $filename = trim($filename,'"');
            header('Content-Disposition: attachment; filename="'.$filename.'"');
            header('Content-Length:'.$res->getHeader('Content-Length')[0]);
            header($res->getHeader('Content-Type')[0]);
            echo $body = $res->getBody();
        }


    }
    elseif ($_GET['_r'] == 1)
    {
        $result = array();
        $result['ipt_body'] = htmlspecialchars_decode($html->find('textarea[name=IPT_BODY]',0)->innertext);
        $result['comments'] = htmlspecialchars_decode($html->find('textarea[name=comments]',0)->innertext);
        $result['mark'] = $html->find('input[name=mark]',0)->value;
        echo json_encode($result);
    }




}


?>